package com.example.infrastructure.api.person;

import com.example.infrastructure.api.person.dto.CompoundPersonDto;
import com.example.infrastructure.api.person.vo.PersonVo;
import com.example.infrastructure.application.OrganizationApplication;
import com.example.infrastructure.application.PersonApplication;
import com.example.infrastructure.domain.person.aggregate.Person;
import com.example.infrastructure.infrastructure.mapper.person.PersonMapper;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityNotFoundException;
import javax.validation.Valid;
import java.util.List;

/**
 * TODO
 *
 * @author lxh
 * @date 2020/11/23 上午11:36
 **/
@RestController
@RequestMapping("/person")
public class PersonApi {
    private final PersonMapper personMapper;
    private final PersonApplication personApplication;
    private final OrganizationApplication organizationApplication;

    public PersonApi(
            PersonMapper personMapper,
            PersonApplication personApplication,
            OrganizationApplication organizationApplication) {
        this.personMapper = personMapper;
        this.personApplication = personApplication;
        this.organizationApplication = organizationApplication;
    }

    @GetMapping("/{personId}")
    public CompoundPersonDto findPerson(@PathVariable String personId) {
        return personApplication
                .findPerson(personId)
                .map(personMapper::toCompoundPersonDto)
                .orElseThrow(() -> new EntityNotFoundException("不存在该人员：" + personId));
    }

    @GetMapping
    public List<CompoundPersonDto> findPerson(PersonVo vo) {
        List<Person> people = personApplication.findPerson(personMapper.toDo(vo));
        return personMapper.toCompoundPersonDtoList(people);
    }

    @PostMapping
    public Person addPerson(@RequestBody @Valid PersonVo vo) {
        return personApplication.save(personMapper.toDo(vo));
    }

    @PutMapping
    public Person updatePerson(@RequestBody @Valid PersonVo vo) {
        return personApplication.update(personMapper.toDo(vo));
    }

    @DeleteMapping("/{personId}")
    public void deletePerson(@PathVariable String personId) {
        personApplication.delete(personId);
    }
}
